package com.mitou.common.interceptor;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.mitou.common.annotation.JsonBindForDictField;
import com.mitou.common.exception.business.BusinessException;
import com.mitou.common.response.ResultCode;
import com.mitou.common.utils.web.BaseDictUtil;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;

/**
 * <p>
 * 系统内字典值转换，在返回前端json时进行字典名称赋值
 * <p/>
 *
 * @author rice
 * @since 2022-01-15
 */
@Component
public class JsonBindSerializer extends JsonSerializer<Object> {

    public JsonBindSerializer() {
    }

    @Override
    public void serialize(Object obj, JsonGenerator gen, SerializerProvider provider) {
        try {
            gen.writeStartObject();
            Field[] list = obj.getClass().getDeclaredFields();
            for (Field field : list) {
                //使用反射工具代替 field.setAccessible(true) field.set(obj, value)可由ReflectionUtils.setField(field,obj,value)代替
                ReflectionUtils.makeAccessible(field);
                String fieldName = field.getName();
                if ("serialVersionUID".equals(fieldName)) {
                    continue;
                }
                Object fieldVal = field.get(obj);
                if (fieldVal instanceof Long) {
                    fieldVal = fieldVal.toString();
                }
                gen.writeObjectField(fieldName, fieldVal);
                JsonBindForDictField ann = AnnotationUtils.findAnnotation(field, JsonBindForDictField.class);
                if (null != ann) {
                    String dictName = ann.value();
                    if ("".equals(dictName)) {
                        dictName = fieldName.concat("Name");
                    }
                    if (null == fieldVal) {
                        gen.writeObjectField(dictName, null);
                    } else {
                        gen.writeObjectField(dictName, BaseDictUtil.getNameById(Long.parseLong(fieldVal.toString())));
                    }
                }
            }
            gen.writeEndObject();
        } catch (Exception e) {
            throw new BusinessException(ResultCode.SYSTEM_DICT_CONVERT_ERROR);
        }
    }
}
